package com.ouc.eddyAlgorithm.service.impl;

import com.ouc.common.utils.DateUtils;
import com.ouc.eddyAlgorithm.domain.VgForecast;
import com.ouc.eddyAlgorithm.service.IVgForecastService;
import com.ouc.eddyAlgorithm.service.IVgTrackService;
import com.ouc.eddyAlgorithm.service.TrackCalculationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author B504
 * @date 2023/3/9
 * @apiNote
 */
@Service
public class TrackCalculationServiceImpl implements TrackCalculationService {
  @Autowired
  IVgTrackService vgTrackService;

  @Autowired
  IVgForecastService vgForecastService;

  @Override
  public boolean getTrackingByTime(Date startTime, Date endTime, Integer level) {
    // 先把之前的结果表清空
    vgTrackService.truncateTable();
    List<Date> timeList = DateUtils.getDateBetweenDate(startTime, endTime, "day");
    List<List<VgForecast>> lists = new ArrayList<>();
    VgForecast vgForecast = new VgForecast();
    for (int i = 0; i < timeList.size(); i++) {
      Map<String, Object> map = new HashMap<>();
      map.put("beginEddyDate", DateUtils.parseDateToStr("yyyy-MM-dd", timeList.get(i)));
      map.put("endEddyDate", DateUtils.parseDateToStr("yyyy-MM-dd", timeList.get(i)));
      vgForecast.setParams(map);
      vgForecast.setEddyLevel(level);
      lists.add(vgForecastService.selectVgForecastList(vgForecast));
    }
    List<VgForecast> vgTrackList = new ArrayList<>();
    List<VgForecast> vgForecastsList0 = lists.get(0);
    //TODO:改进追踪算法，现在只跟第一天的差1度认为同一个涡旋
    for (int i = 0; i < vgForecastsList0.size(); i++) {
      vgTrackList.add(vgForecastsList0.get(i));
      for (int j = 1; j < lists.size(); j++) {
        for (int k = 0; k < lists.get(j).size(); k++) {
          if (Math.sqrt(Math.pow(vgForecastsList0.get(i).getEddyLon() - lists.get(j).get(k).getEddyLon(), 2) + Math.pow(vgForecastsList0.get(i).getEddyLat() - lists.get(j).get(k).getEddyLat(), 2)) < 1) {
            lists.get(j).get(k).setEddyId(vgForecastsList0.get(i).getEddyId());
            vgTrackList.add(lists.get(j).get(k));
          }
        }
      }
    }

    vgTrackService.insertByBatch(vgTrackList);

    return true;
  }
}
